package com.dacool.activity;

import java.io.Serializable;
import java.util.Date;

import android.app.Activity;
import android.app.ActivityGroup;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.Window;
import android.widget.RelativeLayout;
import android.widget.Toast;

import com.dacool.app.sale.R;
import com.dacool.config.Config;
import com.dacool.fragment.BaseFragment;
import com.dacool.fragment.CartFragment;
import com.dacool.fragment.HomeFragment;
import com.dacool.fragment.LoginFragment;
import com.dacool.fragment.ProductListFragment;
import com.dacool.fragment.SearchFragment;
import com.dacool.fragment.SettingsFragment;
import com.dacool.helper.DaCoolHelper;
import com.dacool.helper.DaCoolHelper.CartItemObserver;
import com.dacool.model.DCUser;
import com.dacool.util.SystemUiHider;
import com.dacool.util.ViewUtils;
import com.dacool.view.TabBar;
import com.dacool.view.TabBar.TabSelectionListener;
import com.dacool.view.TabItem;
import com.dacool.view.TabItem.TabItemCustomView;
import com.dacool.view.TitleBar;
import com.dacool.view.TitleBar.TitleBarDelegate;
import com.umeng.update.UmengUpdateAgent;

/**
 * An example full-screen activity that shows and hides the system UI (i.e.
 * status bar and navigation/system bar) with user interaction.
 * 
 * @see SystemUiHider
 */
public class MainActivity extends ActivityGroup implements TitleBarDelegate,
		TabSelectionListener, BaseActivityManager, Serializable,
		CartItemObserver {

	/**
	 * 
	 */
	private static final long serialVersionUID = 278818051424807678L;

	transient public static MainActivity sharedInstance;

	private int currentTab = -1;
	private TabBar mTabBar;
	private TitleBar mTitleBar;
	private String[] mTabs = new String[] { "home", "search", "category",
			"cart", "more" };
	private int[] ids = new int[] { R.drawable.home, R.drawable.search3,
			R.drawable.products, R.drawable.cart, R.drawable.wocool };
	private int[] sids = new int[] { R.drawable.home1, R.drawable.search3,
			R.drawable.products1, R.drawable.cart1, R.drawable.wocool1 };

	private Class fragmentClasses[] = new Class[] { HomeFragment.class,
			SearchFragment.class, ProductListFragment.class,
			CartFragment.class, SettingsFragment.class };

	private RelativeLayout contentView;

	private long lastbackbuttonTime = -1L;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		ViewUtils.init(this);
		Config.sharedConfig().init();
		sharedInstance = this;
		DaCoolHelper.sharedInstance().addCartItemObserver(this);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.activity_main);
		mTabBar = (TabBar) findViewById(R.id.tabbar);
		mTitleBar = (TitleBar) findViewById(R.id.titlebar);
		for (int i = 0; i < mTabs.length; i++) {
			String title = mTabs[i];
			TabItem item = new TabItem();

			item.customView = new TabItemCustomView(this, null);
			item.customView.setImage(ids[i]);
			item.customView.setSelectedImage(sids[i]);
			item.tabName = title;
			mTabBar.addTab(item);
		}

		mTabBar.setTabSelectionListener(this);

		mTitleBar.setDelegate(this);
		contentView = (RelativeLayout) findViewById(R.id.activityContainer);

	}

	@Override
	protected void onPostCreate(Bundle savedInstanceState) {
		super.onPostCreate(savedInstanceState);
		DCUser.sharedUser().load();
		mTabBar.setCurrentTab(0);
		com.umeng.common.Log.LOG = true;
		UmengUpdateAgent.update(this);
	}

	Handler mHideHandler = new Handler();

	@Override
	public void didTapLeftButton() {
		// TODO Auto-generated method stub

	}

	@Override
	public void didTapRightButton() {
		// TODO Auto-generated method stub

	}

	@Override
	public boolean shouldSelectTab(int index) {
		if (index == 1) {
//			Toast.makeText(this, R.string.msg_search_notimplemented,
//					Toast.LENGTH_SHORT).show();
			return false;
		} 
//		else if (index == 2) {
//			Toast.makeText(this, "收藏功能暂未推出", Toast.LENGTH_LONG).show();
//			return false;
//		}
		return true;
	}

	@SuppressWarnings("deprecation")
	@Override
	public void didSelectTab(int index) {
		// TODO Auto-generated method stub
		if (currentTab == index)
			return;

		if (index >= 0 && index < mTabs.length) {

			BaseActivity ca = (BaseActivity) getLocalActivityManager()
					.getCurrentActivity();
			contentView.removeAllViews();
			if (ca != null) {
				// ca.getWindow().getDecorView().setVisibility(View.GONE);
			}
			Intent intent = new Intent(this, BaseActivity.class);
			intent.putExtra(BaseActivity.IntentKeyFragmentClass,
					fragmentClasses[index]);
			Activity a = getLocalActivityManager().getActivity(
					"activity:" + index);
			if (a == null)
				intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
			intent.putExtra("MainActivity", this);
			Window window = getLocalActivityManager().startActivity(
					"activity:" + index, intent);
			// window.getDecorView().setVisibility(View.VISIBLE);
			contentView.addView(window.getDecorView());
		}
	}

	@Override
	public void onBackPressed() {
//		Log.d("test", "backpressed");
		if (getLocalActivityManager().getCurrentActivity() != null
				&& ((BaseActivity) getLocalActivityManager()
						.getCurrentActivity()).handleBackButton()) {
			return;
		} else {
			long pressTime = new Date().getTime();
			if (lastbackbuttonTime <= 0
					|| pressTime - lastbackbuttonTime > 2000) {
				lastbackbuttonTime = pressTime;
				Toast.makeText(this, "再按一次退出", 2000).show();
			} else {
				super.onBackPressed();
			}

		}
	}

	@Override
	public void onResume(BaseActivity a) {
		// TODO Auto-generated method stub
//		Log.d("test", "1");
		mTitleBar.setTitleView(a.getTitleView());
		mTitleBar.setRightButtonItem(a.getRightItem());
		mTitleBar.setLeftButton(a.getLeftItem());
		mTitleBar.setSecondLeftButton(a.getSecondLeftItem());
//		Log.d("test", "2");
	}

	@Override
	public void onPause(BaseActivity a) {
		// TODO Auto-generated method stub

	}

	@Override
	public void activityFragmentChanged(BaseActivity a, boolean pop) {
		// TODO Auto-generated method stub
		mTitleBar.setTitleView(a.getTitleView());
		mTitleBar.setRightButtonItem(a.getRightItem());
		mTitleBar.setLeftButton(a.getLeftItem());
		mTitleBar.setSecondLeftButton(a.getSecondLeftItem());
		// if (!pop)
		// mTitleBar.pushTitleView(a.getTitleView(), "stack:" + currentTab);
		// else
		// mTitleBar.popTitle("stack:" + currentTab);
	}

	public void setCurrentTab(int index) {
		if (this.shouldSelectTab(index))
			mTabBar.setCurrentTab(index);
	}
	
	public void setCurrentTab(int index, Class<? extends BaseFragment> clz){
		if(this.shouldSelectTab(index))
		{
			mTabBar.setCurrentTab(index);
			BaseActivity a = (BaseActivity) getLocalActivityManager().getActivity("activity:"+index);
			a.gotoFragment(clz);
		}
	}

	@Override
	public void cartItemsChanged() {
		// TODO Auto-generated method stub
		int number = DaCoolHelper.sharedInstance().getCartItems().size();
		mTabBar.setBadgeValue(3, number > 0 ? "" + number : "");
	}

}
